External Exam Download Resources Web Applications Games Recycle Bin

Jinja2 if else

templates\template.html

{% if message == "hello!" %}
  <h1>Server says hello!</h1>
{% else %}
  <h1>Server said something else.</h1>
{% endif %}

server.py

from flask import *
app = Flask("branching logic with jinja")

@app.route("/")
def main():
    return render_template("template.html",
                           message = "hello!")
 
app.run(debug=True)

A safer way is to check in the template if a variable is defined first, before trying to print or use its value:

templates\template.html

{% if message is defined %}
  {% if message == "hello!" %}
    <h1>Server says hello!</h1>
  {% else %}
    <h1>Server said something else.</h1>
  {% endif %}
{% else %}
  <h1>Server said nothing.</h1>
{% endif %}